package com.item.action;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.service.BFileService;
import com.item.dao.NoteDetailMapper;
import com.item.dao.model.Note;
import com.item.dao.model.NoteAuthor;
import com.item.dao.model.NoteAuthorExample;
import com.item.dao.model.NoteDetail;
import com.item.dao.model.NoteDetailExample;
import com.item.dao.model.NoteExample;
import com.item.dao.model.NoteLock;
import com.item.dao.model.NoteLockExample;
import com.item.dao.model.NoteShareModel;
import com.item.dao.model.NoteExample.Criteria;
import com.item.dao.model.NoteUserExample;
import com.item.dao.model.SubjectDetail;
import com.item.dao.model.SubjectDetailExample;
import com.item.dao.model.Unread;
import com.item.dao.model.UnreadExample;
import com.item.daoEx.model.NoteEx;
import com.item.exception.JSONRepUtils;
import com.item.service.NoteAuthorService;
import com.item.service.NoteDetailService;
import com.item.service.NoteLockService;
import com.item.service.NoteService;
import com.item.service.NoteUserService;
import com.item.service.SubjectDetailService;
import com.item.service.UnreadService;
import com.item.util.SubjectUtils;

@Controller
public class NoteController {
	@Autowired
	private NoteService noteService;
	
	@Autowired
	private NoteAuthorService authorService;
	
	@Autowired
	private SubjectDetailService subDetailService;
	
	@Autowired
	private NoteDetailService detailService;
	
	@Autowired
	private BFileService fileService;
	
	@Autowired
	private NoteUserService noteUserService;
	
	@Autowired
	private NoteLockService noteLockService;
	@Autowired
	private UnreadService unreadService;
	
	@RequestMapping("/listNote")
	@ResponseBody
	public String list(Page param,Note note) throws Exception{
		NoteExample example = new NoteExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		Criteria criteria = example.createCriteria();
		//以下两个字段用来做筛选  分别是title和source的模糊匹配
		if(note.getSubNum() != null){
			criteria.andSubNumEqualTo(note.getSubNum());
		}
		if(StringUtils.isNotBlank(note.getDescription())){
			criteria.andDescriptionLike("%" + note.getDescription() +"%");
		}
		if(StringUtils.isNotBlank(note.getSubName())){
			criteria.andSubNameEqualTo(note.getSubName());
		}
		if(StringUtils.isNotBlank(note.getWantToSay())){
			criteria.andWantToSayLike("%" + note.getWantToSay() +"%");
		}
		if(StringUtils.isNotBlank(note.getExperience())){
			criteria.andExperienceLike("%" + note.getExperience() +"%");
		}
		if(StringUtils.isNotBlank(note.getSuitable())){
			criteria.andSuitableLike("%" + note.getSuitable() +"%");
		}
		if(StringUtils.isNotBlank(note.getAuthor())){
			criteria.andAuthorEqualTo(note.getAuthor());
		}
		if(note.getIsLocked() != null){
			criteria.andIsLockedEqualTo(note.getIsLocked());
		}
		example.setOrderByClause("top DESC,sub_num ASC");
		List<Note> list = noteService.selectByExample(example);
		for(Note n : list){
			NoteAuthor author = authorService.selectByPrimaryKey(n.getAuthor());
			if(author != null){
				n.setAuthor(author.getName());
			}else{
				n.setAuthor("");
			}
			//再获取笔记本下面的笔记数量
			NoteDetailExample ndex = new NoteDetailExample();
			ndex.createCriteria().andPidEqualTo(n.getId());
			n.setFileSize(detailService.countByExample(ndex));
		}
		return JSONRepUtils.serialize(new Page(PaginationSupport.getContext().getTotalCount(), list), 0);
	}
	
	@RequestMapping("/showlistNote")
	public String list() {
		return "note/noteList";
	}
	
	@RequestMapping("/toEditNote")
	public String toEdit()throws Exception{
		return "/note/noteEdit";
	}
	
	@RequestMapping(value="/saveNote",method=RequestMethod.POST)
	@ResponseBody
	public String save(Note note, HttpSession session,String fileIds)throws Exception{
		try{
			if(StringUtils.isBlank(note.getId())){
				SubjectDetail detail = subDetailService.selectByPrimaryKey(note.getSubId());
				//首先
				note.setSubName(detail.getName());
				//封面路径
				note.setCoverPath(fileService.selectByPrimaryKey(note.getCover()).getFilePath());
				note.setBuyUrl("");
				note.setCommentCount(0);
				note.setPraiseCount(0);
				note.setFile("");
				note.setFilePath("");
				note.setFileSize(0);
				note.setVideoCover("");
				note.setCreateTime(new Date());
				note.setModifyTime(note.getCreateTime());
				note.setTitle("");
				note.setBrowseCount(0);
				NoteExample nex = new NoteExample();
				nex.createCriteria().andSubIdEqualTo(note.getSubId());
				note.setTop(noteService.countByExample(nex)+1);
				//再去更新具体的科目，将具体科目设置为有笔记
			    if(detail.getHasBooks() == 0){
			    	 detail.setHasBooks(1);
						subDetailService.updateByPrimaryKeySelective(detail);
			    }
				noteService.insert(note);
				//再去插入图片详情
				insertDetail(fileIds, note);
				//再更新大神笔记的未读
				UnreadExample unex = new UnreadExample();
				Unread read = new Unread();
				read.setModule1(1);
				unreadService.updateByExampleSelective(read, unex);
			}else{
				note.setModifyTime(new Date());
				noteService.updateByPrimaryKeySelective(note);
				//修改的时候需要注意比较修改前和修改后的情况
				//首先拿到修改前的图片列表
				Map<String,String> map = new HashMap<String,String>();
				map.put("pid", note.getId());
				List<String> previous = detailService.selectImgList(map);
				List<String> tmp = new ArrayList<String>();
				CollectionUtils.addAll(tmp, new Object[previous.size()]);
				Collections.copy(tmp, previous);
				List<String> now = new ArrayList<String>(Arrays.asList(fileIds.split(",")));
				for(int i = 0 ; i < previous.size() ; i++){
					String id = previous.get(i);
					if(tmp.contains(id) && now.contains(id)){
						tmp.remove(id);
						now.remove(id);
					}
				}
//				System.out.println(previous);
//				System.out.println(tmp);
//				System.out.println(now);
				//tmp中剩下的就是要删除的，而now中剩下的是要新加的
				//首先删除detail中的
				for(String id : tmp){
					NoteDetailExample ndex = new NoteDetailExample();
					ndex.createCriteria().andImgEqualTo(id).andPidEqualTo(note.getId());
					List<NoteDetail> details = detailService.selectByExample(ndex);
					if(details.size() > 0){
						NoteDetail detail = details.get(0);
						NoteUserExample nuex = new NoteUserExample();
						nuex.createCriteria().andPidEqualTo(detail.getId());
						noteUserService.deleteByExample(nuex);
						//再删除详情里的说
						detailService.deleteByPrimaryKey(detail.getId());
					}
				}
				//如果有新增的，再添加新增的图片
//				for(String id : now){
//					//首先向detail中添加一条记录
////					insertDetail(id,note);
//					//再向note user表中所有有该笔记的用户添加一条
//					NoteUserExample nuex = new NoteUserExample();
//					nuex.createCriteria().andNoteIdEqualTo(note)
//				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		return "{\"success\":true}";
	}
	
	public void insertDetail(String files,Note note){
		String[] ids = files.split(",");
		int count = ids.length;
		for(String id : ids){
			NoteDetail detail = new NoteDetail();
			detail.setPid(note.getId());
			detail.setImg(id);
			detail.setImgPath("");
			detail.setIsAd(0);
			detail.setOrders(count);
			detail.setRemark("");
			detail.setSubName(SubjectUtils.getSubjectByType(note.getSubNum()));
			detail.setSubNumber(note.getSubNum());
			detail.setCreateTime(new Date());
			detailService.insert(detail);
			count --;
		}
		
	}
	
	@RequestMapping(value="/findByIdNote")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		Note n = noteService.selectByPrimaryKey(id);
		Map<String,String> map = new HashMap<String,String>();
		map.put("pid", id);
		n.setTitle(detailService.selectImgList(map).toString().replaceAll("\\[|\\]|\\s", ""));
		return JSONRepUtils.serialize(n, 0);
	}
	
	@RequestMapping("/addNoteNewMessage")
	@ResponseBody
	public String addEssenceNewMessage() throws Exception {
		String result;
		try{
			UnreadExample udex = new UnreadExample();
			Unread read = new Unread();
			read.setModule1(1);
			unreadService.updateByExampleSelective(read, udex);
			result = "{\"success\":true}";
		}catch(Exception e){
			result = "{\"success\":false}";
		}
		return result;
	}
	
	@RequestMapping("/delNote")
	@ResponseBody
	public String del(String id,String url,String subId,HttpSession session)throws Exception{
//		WebPageFileController fileController = new WebPageFileController();
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			noteService.deleteByPrimaryKey(ids[i]);
			//再去删除笔记详情中的
			NoteDetailExample ndex = new NoteDetailExample();
			ndex.createCriteria().andPidEqualTo(ids[i]);
			detailService.deleteByExample(ndex);
			//再去删除笔记用户中的记录
			NoteUserExample nuex = new NoteUserExample();
			nuex.createCriteria().andNoteIdEqualTo(ids[i]);
			noteUserService.deleteByExample(nuex);
//			fileController.deleteFile(urls[i]);
		}
		String[] subs = subId.split(",");
		for(String sub : subs){
			NoteExample nex = new NoteExample();
			nex.createCriteria().andSubIdEqualTo(sub);
			//说明这个科目下已经没有笔记
			if(noteService.countByExample(nex) < 1){
				SubjectDetail detail = new SubjectDetail();
				detail.setId(sub);
				detail.setHasBooks(0);
				subDetailService.updateByPrimaryKeySelective(detail);
			}
		}
		//删除完成之后再判断下
		return "{\"success\":true}";
	}
	
	public List<NoteEx> convertToNoteEx(List<Note> lists){
		List<NoteEx> listEx = new ArrayList<NoteEx>();
		for(Note note : lists){
			NoteEx ex = new NoteEx();
			ex.setId(note.getId());
			ex.setAuthor(note.getAuthor());
			
		}
		return listEx;
	}
	
	@RequestMapping("/getAllAuthors")
	@ResponseBody
	public String getAllAuthors(){
		NoteAuthorExample naex = new NoteAuthorExample();
		List<NoteAuthor> lists = authorService.selectByExample(naex);
		return JSONRepUtils.serialize(lists, 0);
	}
	
	@RequestMapping("/getAllSubjectDetails")
	@ResponseBody
	public String getAllSubjectDetails(String subNum){
		SubjectDetailExample naex = new SubjectDetailExample();
		SubjectDetailExample.Criteria criteria = naex.createCriteria();
		if(StringUtils.isNotBlank(subNum)){
			criteria.andSubIdEqualTo(subNum);
		}
		List<SubjectDetail> lists = subDetailService.selectByExample(naex);
		return JSONRepUtils.serialize(lists, 0);
	}
	
	
	@RequestMapping("/moveUpNote")
	@ResponseBody
	public String moveUp(String id,HttpSession session) throws Exception {
		return processMove(id, 0);
	}
	
	@RequestMapping("/moveDownNote")
	@ResponseBody
	public String moveDown(String id,HttpSession session) throws Exception {
		return processMove(id, 1);
	}
	
	/**
	 * 操作上移下移的动作
	 * @param uid
	 * @param type
	 * @return
	 */
	public String processMove(String uid,int type){
		
		Note now = noteService.selectByPrimaryKey(uid);
		if(now == null){
			return "{\"success\":false}";
		}
		NoteExample sdex = new NoteExample();
		if(type == 0){
			sdex.createCriteria().andSubIdEqualTo(now.getSubId()).andTopGreaterThan(now.getTop());
			sdex.setOrderByClause("top ASC");
		}else{
			sdex.createCriteria().andSubIdEqualTo(now.getSubId()).andTopLessThan(now.getTop());
			sdex.setOrderByClause("top DESC");
		}
		PaginationSupport.setContext(1, 1, null);
		List<Note> nexts = noteService.selectByExample(sdex);
		if(nexts == null || nexts.size() == 0){
			return "{\"success\":false}";
		}
		Note next = nexts.get(0);
		Integer top = next.getTop();
		next.setTop(now.getTop());
		noteService.updateByPrimaryKeySelective(next);
		now.setTop(top);
		noteService.updateByPrimaryKeySelective(now);
		return "{\"success\":true}";
	}
	
	@RequestMapping("/cancelNoteLock")
	@ResponseBody
	public String cancelLock(String id,HttpSession session) throws Exception {
		return updateNoteLock(id,0,0);
	}
	
	@RequestMapping("/addNoteLock")
	@ResponseBody
	public String addLock(String id,HttpSession session) throws Exception {
		return updateNoteLock(id,1,0);
	}
	
	@RequestMapping("/addNoteLockAbsolute")
	@ResponseBody
	public String addLockAbsolute(String id,HttpSession session) throws Exception {
		return updateNoteLock(id,1,1);
	}
	
	public String updateNoteLock(String id, int isLocked,int type){
		String result;
		try{
			Note note = new Note();
			note.setId(id);
			note.setIsLocked(isLocked);
			noteService.updateByPrimaryKeySelective(note);
			if(type == 1){
				//这时候是完全加锁，需要把之前用户的分享记录全部删除
				NoteLockExample nlex = new NoteLockExample();
				nlex.createCriteria().andPidEqualTo(id);
				noteLockService.deleteByExample(nlex);
			}
			result = "{\"success\":true}";
		}catch(Exception e){
			result = "{\"success\":false}";
		}
		return result;
	}
	
	
}

